<template>
    <page-meta :page-style="$theme.pageStyle">
        <!-- #ifndef H5 -->
        <navigation-bar
            :front-color="$theme.navColor"
            :background-color="$theme.navBgColor"
        />
        <!-- #endif -->
    </page-meta>
    <view class="news-detail bg-white">
        <!-- #ifdef H5 -->
        <navHead :title='newsData.title'></navHead>
        <!-- #endif -->
        <!-- 咨询内容 -->
        <view class="news-detail-section bg-white p-[24rpx]" v-if='isLogin'>
            <view class="mt-[20rpx] content-container">
                <template v-if="newsData.listens && newsData.listens.listens && newsData.listens.listens.length">
                    <template v-for="(audio, index) in audioList">
                        <AudioPlayer :data='audio' :index='index'
                                     @pause='pauseAudio'
                                     @change-progress='changeProgree'
                                     @drag-progress='dragProgress'
                                     @play='playAudio'
                        />
                        <img v-for="(image, index) in images[audio['key']]" :src='image' mode="widthFix" @click="clickImg(image)"/>
                    </template>
                </template>
                <template v-else>
                    <AudioMedia :audio-url='newsData.listen' v-if='newsData.listen'/>
                    <img v-for="(image, index) in newsData.images" :src='image' mode="widthFix" @click="clickImg(image)"/>
                </template>
            </view>
        </view>
        <view v-else>
            <navigator url="/pages/login/login">
                <view class='p-[20rpx] login-text'>
                    去登录
                </view>
            </navigator>
        </view>
    </view>
    <next-watermark :watermark="watermark" :opacity='0.1' :custom-top='20'></next-watermark>

    <q-previewImage ref="previewImage" :urls="imgs"  @open="open" @close="close"></q-previewImage>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { onLoad,onShow, onUnload,onHide } from '@dcloudio/uni-app'
import { getArticleDetail, articleScreenshot } from '@/api/news'
import AudioPlayer from '@/components/audio-player/audio-player.vue'
import AudioMedia from '@/components/audio-media/audio-media.vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { useRouter } from 'uniapp-router-next'
const router = useRouter()

const userStore = useUserStore()
const { userInfo, isLogin } = storeToRefs(userStore)

const watermark = ref(`<h3>${userInfo.value.name}</h3><p >${userInfo.value.card_no}</p>`)

const newsData = ref<any>({})
let newsId = ''

const previewImage = ref(null);
const imgs = ref([]);
const open = () => { //监听组件显示 （隐藏TabBar和NavigationBar，隐藏video原生组件）
    // uni.hideTabBar()
    // uni.setNavigationBarColor({
    // 	frontColor: '#000000', // 设置前景色为黑色
    // 	backgroundColor: '#000000', // 设置背景色为黑色
    // })
    // data.videoShow = false
}

const close = () => { //监听组件隐藏 （显示TabBar和NavigationBar，显示video原生组件）
    // uni.showTabBar()
    // uni.setNavigationBarColor({
    // 	frontColor: '#ffffff', // 设置前景色为白色
    // 	backgroundColor: '#000000', // 设置背景色为黑色
    // })
    // data.videoShow = true
}

const audioAction = {
    method: 'pause'
}

function getName(filename) {
    const info = filename.split('/');
    const file = info[info.length - 1];
    const fileinfo = file.split('.')
    return fileinfo[0];
}

function clickImg(path) {
    imgs.value = newsData.value.images
    nextTick(()=>{
        previewImage.value.open(path); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
    })
}

const playStatus = ref([])
const images = ref([]);
const audioList = ref([])
let innerAudioContext = ''

const getData = async (id) => {
    newsData.value = await getArticleDetail({ id })
    uni.setNavigationBarTitle({
        title: newsData.value.title
    })
    innerAudioContext = uni.createInnerAudioContext();

    if (newsData.value.listen) {
        if (newsData.value.listens && newsData.value.listens.listens && newsData.value.listens.listens.length) {
            audioList.value = newsData.value.listens.listens
            images.value = newsData.value.listens.pdfs
            innerAudioContext.src = audioList.value[0].url;

        } else {
            audioList.value = []
            images.value = [];
        }
    }
}

const videoContext = ref(null);
const timer = ref(null);

function playAudio(index){
    console.log('play')
    audioList.value.forEach((item, i) => {
        if (index !== i) {
            item.status = 'pause'
        }
    })
    console.log(audioList.value);
    innerAudioContext.offCanplay();
    innerAudioContext.offTimeUpdate();
    innerAudioContext.offEnded;


    const audio = audioList.value[index];
    if (dateFormart(audio.currentTime) === dateFormart(audio.duration)) {
        audio.progress = 100
    }

    innerAudioContext.volume = 1
    innerAudioContext.stop()
    innerAudioContext.src = audio.url
    audio.status = 'play'

    innerAudioContext.sessionCategory = "soloAmbient"
    innerAudioContext.seek(Number(audio.progress) === 100 ? 0 : (audio.currentTime ? audio.currentTime : 0))
    innerAudioContext.startTime = Number(audio.progress.value) === 100 ? 0 : (audio.currentTime ? audio.currentTime : 0)
    innerAudioContext.play()
    onCanplay(audio);
}

function dragProgress(){
    console.log('dragProgress')
    innerAudioContext.pause()
}

function changeProgree(index, progress){
    console.log('changeProgree')
    const audio = audioList.value[index];
    audio.progress = progress
    audio.currentTime = audio.duration * (progress / 100)
    playAudio(index)
}

const onCanplay = (audio) => {
    innerAudioContext.onCanplay(() => {
        audio.currentTime = innerAudioContext.currentTime
    })
    innerAudioContext.onTimeUpdate(() => {
        audio.currentTime = innerAudioContext.currentTime
        audio.progress = (innerAudioContext.currentTime / innerAudioContext.duration * 100).toFixed(2)
    })
    innerAudioContext.onEnded(() => {
        audio.status = 'pause'
    })
}

function pauseAudio(index){
    console.log('pauseAudio')
    const audio = audioList.value[index];
    innerAudioContext.pause()
    audio.status = 'pause'
}

const dateFormart = (value) => {
    value = Number(value).toFixed(0)
    let hour = Math.floor(value / 3600)
    let minute = Math.floor((value - hour * 3600) / 60)
    let second = value - hour * 3600 - minute * 60
    hour = hour < 10 ? `0${hour}` : hour
    minute = minute < 10 ? `0${minute}` : minute
    second = second < 10 ? `0${Math.floor(second)}` : Math.floor(second)
    return `${minute}:${second}`
}

onLoad((options: any) => {
    newsId = options.id
    getData(newsId)

    videoContext.value = uni.createVideoContext('videoPlayer', this);

    //防录屏/截屏
    let platform = uni.getSystemInfoSync().platform;
    console.log(platform,'设备标识')
    console.log(uni.getSystemInfoSync())

    //安卓手机
    if (platform === "android") {
        console.log(platform,'设备标识111---')
        if (uni.setVisualEffectOnCapture) {
            uni.setVisualEffectOnCapture({
                visualEffect: 'hidden',
                success: (res)=>{
                    console.log('success录屏',res);
                }
            })
        }
    } else if (platform === 'ios') {
        uni.onUserCaptureScreen(async function (res) {
            console.log('用户截屏了')
            const screenInfo = await articleScreenshot({ id: newsId })
            if (screenInfo['disabled']) {
                uni.showModal({
                    content:'您已截屏超过两次，账号已禁用。',
                    showCancel:false,
                    success: (res) => {
                        if(res.confirm){
                            userStore.logout()
                            router.redirectTo('/pages/login/login')
                        }
                    }
                })
            } else {
                uni.showModal({
                    content:'此应用禁止截屏，截屏两次将做封号处理。',
                    showCancel:false,
                    success: (res) => {
                        if(res.confirm){
                        }
                    }
                })
            }
        })

        //苹果手机
        timer.value = setInterval(()=>{
            uni.getScreenRecordingState({
                success: (res)=>{
                    console.log('success录屏22',res);
                    if(res.state=='on'){
                        videoContext.value.pause() //暂停视频播放
                        uni.showModal({
                            content:'此页面不允许录屏',
                            showCancel:false,
                            success: (res) => {
                                if(res.confirm){
                                    uni.navigateBack()
                                }
                            }
                        })
                    }
                }
            })
        },2000)
    }
})

onUnload(() =>{
    console.log('onUnload')
    if (uni.setVisualEffectOnCapture) {
        uni.setVisualEffectOnCapture({
            visualEffect: 'none',
            success: (res)=>{
                console.log('success',res);
            },
            complete: function(res) {
                console.log('complete',res);
            }
        })
    }
    if(timer.value) {
        clearTimeout(timer.value);
        timer.value = null;
    }
    if (innerAudioContext) {
        console.log('innerAudioContext destroy')
        innerAudioContext.destroy();
    }
})

onShow(() => {
    if (uni.setVisualEffectOnCapture) {
        uni.setVisualEffectOnCapture({
            visualEffect: 'hidden',
            complete: function(res) {}
        })
    }
})
// 页面隐藏和销毁时需要释放防截屏录屏设置
onHide(() => {
    if (uni.setVisualEffectOnCapture) {
        uni.setVisualEffectOnCapture({
            visualEffect: 'none',
            complete: function(res) {}
        })
    }
    if(timer.value) {
        clearTimeout(timer.value);
        timer.value = null;
    }
})

</script>

<style lang="scss">
.login-text{
    height: 100rpx;
    line-height: 72rpx;
    border-radius: 10rpx;
    text-align: center;
    width: 80%;
    margin: 16rpx auto;
    background:#3b1e7c!important;
    color:#fff;
}
.news-detail {
    height: 100%;

    &-header {
        border-bottom: 2rpx solid #f8f8f8;
    }

    &-section {
        .summary {
            border-radius: 12rpx;
            background-color: #f7f7f7;
        }
    }

    .panel-btn {
        position: fixed;
        right: 30rpx;
        height: 80rpx;
        bottom: 80rpx;
        border-radius: 40rpx;
        background: rgba(255, 255, 255, 0.95);
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.16);
    }
}
.content-container{
    position: relative;

    img,image{
        width:100%;
    }

    .audio-btns{
        //text-align: center;
        //position: absolute;
        //top: 0;
        //left: 0;
        width: 100%;
        text-align: center;

        img,image{
            width: 100rpx;
            height: 100rpx;
        }
    }
}

</style>
